package com.wb.utils

/**
 * Unicode 编码互转
 *
 * @author 祁雪
 */
class UnicodeUtil {

    companion object {

        fun Int.toHexString(): String = Integer.toHexString(this)

        /**
         * 字符转 Unicode
         */
        fun encode(char: Char) = "\\u${char.toInt().toHexString()}"

        /**
         * 字符串转 Unicode
         */
        fun encode(text: String) = text
            .toCharArray()
            .map { encode(it) }
            .joinToString(separator = "", truncated = "")

        /**
         * Unicode转字符串
         */
        fun decode(encodeText: String): String {
            fun decode1(unicode: String) = unicode.toInt(16).toChar()
            val unicodes = encodeText.split("\\u")
                .map { if (it.isNotBlank()) decode1(it) else null }.filterNotNull()
            return String(unicodes.toCharArray())
        }
    }

}